#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    connect(ui->textBrowser,&QTextBrowser::textChanged,[=](){
        ui->textBrowser->moveCursor(QTextCursor::End);
    });
}

Widget::~Widget()
{
    delete ui;
}


void Widget::on_pushButton_clicked()
{
#if 1
    QString _log = "";
    // 设置Python的安装路径
    wchar_t pythonHome[100] = L"C:\\Tools\\Python\\Python36";
    // 检测默认路径是否存在
    if(!QDir(QString::fromStdWString(pythonHome)).exists())
    {
        wcscpy_s(pythonHome,L"D:\\PrJ\\QtProject\\TestQt5UsePyScriptDemo1\\Python36");
    }
    Py_SetPythonHome(pythonHome); //使用宽字符型字符串因为Py_SetPythonHome接收的是wchar_t*
    //修改后路径
    _log = QString::fromStdWString(pythonHome);
    debug(_log);
    // 初始化Python解释器
    Py_Initialize();
    if(Py_IsInitialized())
    {
        _log = "Pyinit Ok ...";
    }
    else {
        _log = "Pyinit Ng ...";
    }
    debug(_log);

    // 清理并退出Python解释器
    Py_Finalize();
#endif
}

void Widget::on_pushButton_2_clicked()
{
    QString app_path = QCoreApplication::applicationDirPath();
    const wchar_t *wstr = reinterpret_cast<const wchar_t *>(app_path.utf16());
    Py_SetPythonHome((wchar_t *)wstr);
}

void Widget::debug(QString s)
{
    ui->textBrowser->append(s);
    qDebug() << s;
}
